using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;

using MSOutlook = Microsoft.Office.Interop.Outlook;
using MSOffice = Microsoft.Office.Core;
using Utility = Microsoft.Sample.Outlook.Utility;
using System.ComponentModel;
using System.Diagnostics;
using Microsoft.Office.Tools.Outlook;

namespace Microsoft.Sample.Outlook.CRMIntegration
{
	public partial class ThisApplication
    {
        #region Instance Variable
        Utility.CustomItemManager _itemManager = null;
		Utility.CommandBarManager _commandbarManager = null;
        internal static MSOffice.IRibbonUI _ribbon;              // Ribbon UI reference
        #endregion
       
        #region ThisApplication_Startup/Shutdown
        private void ThisApplication_Startup(object sender, System.EventArgs e)
        {
            
            //Login session
            string _accountName = "Reussi";
            PIMDataSetTableAdapters.AccountsTableAdapter accountsTableAdapter = new PIMDataSetTableAdapters.AccountsTableAdapter();
            Utility.GlobalClass.AccountID = (Guid)accountsTableAdapter.GetAccountID(_accountName);
            Utility.GlobalClass.AccountName = _accountName;
            ThisApplication.ConfigureDataDirectory(this.GetType());
            
            try
            {
                _itemManager = new Utility.CustomItemManager(this.Application, _ribbon);
                _commandbarManager = new Utility.CommandBarManager(this.Application);
        
                //CreateConvertToolbar();
                //CreateCRMMenu();

                //CreateSyncToolbar();
        
                //CreateCRMTodayFolders();
                CreatePIMTodayFolders();       
                
            }
            catch(Exception ex)
            {

                #if DEBUG
                        MessageBox.Show(ex.Message, ex.Source);
                #else
                        MessageBox.Show("The Outlook CRM Integration Sample Add-in failed to load.", "Outlook CRM Integration Sample", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                #endif

                        LogException(ex);
                        ShutdownAddin();
             }
             

        }
        
        public static void LogException(Exception ex)
        {
            string source = Properties.Resources.CasPolicyName;

            // Create the source, if it does not already exist.
            if (!EventLog.SourceExists(source))
            {
                EventLog.CreateEventSource(source, "Application");
            }

            // Create an EventLog instance and assign its source.
            EventLog myLog = new EventLog();
            myLog.Source = source;

            // Write an informational entry to the event log.    
            myLog.WriteEntry(ex.Message, System.Diagnostics.EventLogEntryType.Error);
        }

        private void ThisApplication_Shutdown(object sender, System.EventArgs e)
        {
            ShutdownAddin();
        }

        private void ShutdownAddin()
        {
            MSOutlook.MAPIFolder root = Utility.Folder.GetRootFolder(this.Application.Session);
            //MSOutlook.MAPIFolder crmFolder = Utility.Folder.GetFolder(root, Properties.Resources.CRMFolderName);
            MSOutlook.MAPIFolder pimFolder = Utility.Folder.GetFolder(root, Utility.GlobalClass.AccountName + "Today");

            if (pimFolder != null)
            {
                pimFolder.WebViewOn = false;

                MSOutlook.MAPIFolder personalFolder = Utility.Folder.GetFolder(pimFolder, Properties.Resources.PersonalFolderName);
                if (personalFolder != null)
                {
                    foreach (MSOutlook.MAPIFolder folder in personalFolder.Folders)
                    {
                        folder.WebViewOn = false;
                    }
                }
            }
            
            _itemManager.Shutdown();
            _commandbarManager.Shutdown();
        }   
        #endregion

        #region Create Toolbar and Menubar control
        private void CreateConvertToolbar()
		{
            Utility.Toolbar crmToolbar = new Utility.Toolbar("Outlook.CRMIntegration  Convert");
			Utility.ToolbarButton btnCreateActivity = new Utility.ToolbarButton("Convert to CRM Activity");
            Utility.ToolbarButton btnCreateOpportunity = new Utility.ToolbarButton("Convert to CRM Opportunity");

			btnCreateActivity.Click += new EventHandler<Utility.CommandBarEventArgs>(btnCreateActivity_Click);
			btnCreateOpportunity.Click += new EventHandler<Utility.CommandBarEventArgs>(btnCreateOpportunity_Click);

			crmToolbar.Controls.Add(btnCreateActivity);
			crmToolbar.Controls.Add(btnCreateOpportunity);

            crmToolbar.BeforeShow += new EventHandler<Utility.BeforeShowCommandBarEventArgs>(crmToolbar_BeforeShow);

            _commandbarManager.RegisterCommandBar(crmToolbar);
		}
        /*
        private void CreateSyncToolbar()
        {
            Utility.Toolbar crmToolbar = new Utility.Toolbar("Outlook.CRMIntegration  SyncService");
            Utility.ToolbarButton btnSync = new Utility.ToolbarButton("Sync PIM");
            //Utility.ToolbarButton btnCreateOpportunity = new Utility.ToolbarButton("Convert to CRM Opportunity");

            btnSync.Click += new EventHandler<Utility.CommandBarEventArgs>(btnSync_Click);
            //btnCreateOpportunity.Click += new EventHandler<Utility.CommandBarEventArgs>(btnCreateOpportunity_Click);

            crmToolbar.Controls.Add(btnCreateActivity);
            crmToolbar.Controls.Add(btnCreateOpportunity);

            crmToolbar.BeforeShow += new EventHandler<Utility.BeforeShowCommandBarEventArgs>(crmToolbar_BeforeShow);

            _commandbarManager.RegisterCommandBar(crmToolbar);
        }
        */
        private void CreateCRMMenu()
        {
            Utility.Menu crmMenu = new Utility.Menu("&CRM Integration Sample", Utility.CommandBarWindowType.ExplorersOnly);
            Utility.MenuItem miCreateActivity = new Utility.MenuItem("Create CRM Activity");
            Utility.MenuItem miCreateOpportunity = new Utility.MenuItem("Create CRM Opportunity");

            miCreateActivity.Click += new EventHandler<Utility.CommandBarEventArgs>(miCreateActivity_Click);
            miCreateOpportunity.Click += new EventHandler<Utility.CommandBarEventArgs>(miCreateOpportunity_Click);

            crmMenu.MenuItems.Add(miCreateActivity);
            crmMenu.MenuItems.Add(miCreateOpportunity);

            _commandbarManager.RegisterCommandBar(crmMenu);

        }
        #endregion

        #region Toolbar and Menubar Events
        void miCreateOpportunity_Click(object sender, Utility.CommandBarEventArgs e)
        {
            ItemForms.OpportunityForm form = new ItemForms.OpportunityForm();
            form.Show();

        }

        void miCreateActivity_Click(object sender, Utility.CommandBarEventArgs e)
        {
            ItemForms.ActivityForm form = new ItemForms.ActivityForm();
            form.Show();
        }

        void crmToolbar_BeforeShow(object sender, Utility.BeforeShowCommandBarEventArgs e)
        {
            e.Enabled = false;

            if (e.CurrentItem == null)
                return;

            if (e.CurrentItem.Class == MSOutlook.OlObjectClass.olMail ||
                e.CurrentItem.Class == MSOutlook.OlObjectClass.olAppointment)
            {
                e.Enabled = true;
            }
        }

		void btnCreateOpportunity_Click(object sender, Utility.CommandBarEventArgs e)
		{
			ItemForms.OpportunityForm form = new ItemForms.OpportunityForm();
			form.Show();
			form.CopyDataFromItem(e.CurrentItem);
		}

		void btnCreateActivity_Click(object sender, Utility.CommandBarEventArgs e)
		{
			ItemForms.ActivityForm form = new ItemForms.ActivityForm();
			form.Show();
			form.CopyDataFromItem(e.CurrentItem);
        }
        /*
        void btnSync_Click(object sender, Utility.CommandBarEventArgs e)
        {
            ItemForms.ActivityForm form = new ItemForms.ActivityForm();
            form.Show();
            form.CopyDataFromItem(e.CurrentItem);
        }
        */
        #endregion

        #region Create and Sync Folder
        private void CreatePIMTodayFolders()
        {
            MSOutlook.MAPIFolder root = Utility.Folder.GetRootFolder(this.Application.Session);

            MSOutlook.MAPIFolder pimFolder = Utility.Folder.CreateFolder(
                root, Utility.GlobalClass.AccountName+"Today");//Properties.Resources.PIMFolderName

            CreatePersonalFolder(pimFolder);

            
            
            //pimFolder.WebViewURL = Utility.FolderHomePage.RegisterType(typeof(FolderHomePages.CRMTodayView));
            //pimFolder.WebViewOn = true;

            //MSOutlook.MAPIFolder accountsFolder = Utility.Folder.CreateFolder(
                //pimFolder, Properties.Resources.AccountsFolderName);

            //CrmDataSetTableAdapters.AccountsTableAdapter adapter = new CrmDataSetTableAdapters.AccountsTableAdapter();
            //CrmDataSet.AccountsDataTable table = adapter.GetData();
            //Utility.SyncEngine.SyncFolders<CrmDataSet.AccountsRow>(accountsFolder, table.Rows, SyncAccountFolder);
            //adapter.Update(table);

        }

        private void CreatePersonalFolder(MSOutlook.MAPIFolder parentFolder)
        {
            MSOutlook.MAPIFolder personalFolder = Utility.Folder.CreateFolder(
                parentFolder, Properties.Resources.PersonalFolderName);
            personalFolder.WebViewURL = Utility.FolderHomePage.RegisterType(typeof(FolderHomePages.PersonalFolderToday));
            personalFolder.WebViewOn = true;
            
            //Create personal contacts folder (Sync contacts)
            MSOutlook.MAPIFolder personalContactFolder = Utility.Folder.CreateFolder(
                personalFolder,
                Utility.GlobalClass.AccountName+"'s"+Properties.Resources.ContactsFolderName,
                MSOutlook.OlDefaultFolders.olFolderContacts);
            //!Important To copy item from other folder for saving that item to local database, you must do follow this step
            //1.After you copy the item , you must open that item window(item inspector)
            //2.If you want to save that item to local database you must CHANGE SOME VALUE OF SOME(OR ONCE) ITEM'S ATTRIBUTE and then choose save and close function.
            //Because if you not change the item's value that you copy. The OnWrite Event will not occour This is the native bahavior of outlook...these is make program Bug godddd.
            _itemManager.RegisterWriteHandler(personalContactFolder, new CancelEventHandler(OnContactWrite));
            _itemManager.RegisterDeleteHandler(personalContactFolder, new CancelEventHandler(OnContactDelete));
            
            PIMDataSetTableAdapters.ContactsTableAdapter contactsTableAdapter = new PIMDataSetTableAdapters.ContactsTableAdapter();
            PIMDataSet.ContactsDataTable contactsDataTable = contactsTableAdapter.GetDataByAccountID(Utility.GlobalClass.AccountID);
            Utility.SyncEngine.SyncItems<PIMDataSet.ContactsRow>(personalContactFolder, contactsDataTable.Rows, Utility.SyncDirection.ItemToOutlook);
            contactsTableAdapter.Update(contactsDataTable);
            ////////////////////

            //Create personal appointments folder (Sync Appointment)
            
            MSOutlook.MAPIFolder personalAppointmentFolder = Utility.Folder.CreateFolder(
                personalFolder,
                Utility.GlobalClass.AccountName + "'s" + Properties.Resources.AppointmentsFolderName,
                MSOutlook.OlDefaultFolders.olFolderCalendar);
            _itemManager.RegisterWriteHandler(personalAppointmentFolder, new CancelEventHandler(OnAppointmentWrite));
            _itemManager.RegisterDeleteHandler(personalAppointmentFolder, new CancelEventHandler(OnAppointmentDelete));

            PIMDataSetTableAdapters.AppointmentsTableAdapter appointmentsTableAdapter = new PIMDataSetTableAdapters.AppointmentsTableAdapter();
            PIMDataSet.AppointmentsDataTable appointmentsDataTable = appointmentsTableAdapter.GetDataByAccountID(Utility.GlobalClass.AccountID);
            Utility.SyncEngine.SyncItems<PIMDataSet.AppointmentsRow>(personalAppointmentFolder, appointmentsDataTable.Rows, Utility.SyncDirection.ItemToOutlook);
            appointmentsTableAdapter.Update(appointmentsDataTable);
             
            /*Custom form
            MSOutlook.MAPIFolder personalAppointmentFolder = Utility.Folder.CreateFolder(
                personalFolder,
                Properties.Resources.AppointmentsFolderName,
                MSOutlook.OlDefaultFolders.olFolderCalendar);
            _itemManager.RegisterCustomForm(personalAppointmentFolder, typeof(ItemForms.AppointmentForm));

            PIMDataSetTableAdapters.AppointmentsTableAdapter appointmentsTableAdapter = new PIMDataSetTableAdapters.AppointmentsTableAdapter();
            PIMDataSet.AppointmentsDataTable appointmentsDataTable = appointmentsTableAdapter.GetDataByAccountID(Utility.GlobalClass.AccountID);
            Utility.SyncEngine.SyncItems<PIMDataSet.AppointmentsRow>(personalAppointmentFolder, appointmentsDataTable.Rows, Utility.SyncDirection.ItemToOutlook);
            appointmentsTableAdapter.Update(appointmentsDataTable);
            */
            //view function beside explorer
            /*
            MSOutlook.View personalAppointmentView = personalAppointmentFolder.Views[Properties.Resources.AppointmentsViewName];
            if (personalAppointmentView == null)
                personalAppointmentView = personalAppointmentFolder.Views.Add(
                    Properties.Resources.AppointmentsViewName,
                    MSOutlook.OlViewType.olTableView,
                    MSOutlook.OlViewSaveOption.olViewSaveOptionThisFolderEveryone);

            personalAppointmentView.XML = Properties.Resources.AppointmentView;
            personalAppointmentView.Save();
            personalAppointmentView.Apply();
             * */


        }
        
		private void SyncAccountFolder(MSOutlook.MAPIFolder accountFolder, CrmDataSet.AccountsRow account)
		{
			//accountFolder.WebViewURL = Utility.FolderHomePage.RegisterType(typeof(FolderHomePages.AccountToday));
			accountFolder.WebViewOn = true;

			SyncActivities(accountFolder, account);

			SyncContacts(accountFolder, account);

			SyncOpportunities(accountFolder, account);

		}
        
		private void SyncOpportunities(MSOutlook.MAPIFolder accountFolder, CrmDataSet.AccountsRow account)
		{
			MSOutlook.MAPIFolder opportunityFolder = Utility.Folder.CreateFolder(
				accountFolder,
				Properties.Resources.OpportunitiesFolderName,
				MSOutlook.OlDefaultFolders.olFolderInbox);
			_itemManager.RegisterCustomForm(opportunityFolder, typeof(ItemForms.OpportunityForm));

			CrmDataSetTableAdapters.OpportunitiesTableAdapter opportunitiesAdapter = new CrmDataSetTableAdapters.OpportunitiesTableAdapter();
			CrmDataSet.OpportunitiesDataTable opportunitiesTable = opportunitiesAdapter.GetDataByAccountID(account.LocalID);
			Utility.SyncEngine.SyncItems<CrmDataSet.OpportunitiesRow>(opportunityFolder, opportunitiesTable.Rows, Utility.SyncDirection.ItemToOutlook);
			opportunitiesAdapter.Update(opportunitiesTable);

			MSOutlook.View opportunityView = opportunityFolder.Views[Properties.Resources.OpoortunitiesViewName];
			if (opportunityView == null)
				opportunityView = opportunityFolder.Views.Add(
					Properties.Resources.OpoortunitiesViewName,
					MSOutlook.OlViewType.olTableView,
					MSOutlook.OlViewSaveOption.olViewSaveOptionThisFolderEveryone);

			opportunityView.XML = Properties.Resources.OpportunityView;
			opportunityView.Save();
			opportunityView.Apply();
		}
        
		private void SyncContacts(MSOutlook.MAPIFolder accountFolder, CrmDataSet.AccountsRow account)
		{
			MSOutlook.MAPIFolder contactFolder = Utility.Folder.CreateFolder(
				accountFolder,
				Properties.Resources.ContactsFolderName,
				MSOutlook.OlDefaultFolders.olFolderContacts); 
			_itemManager.RegisterWriteHandler(contactFolder, new CancelEventHandler(OnContactWrite));

			CrmDataSetTableAdapters.ContactsTableAdapter contactsAdapter = new CrmDataSetTableAdapters.ContactsTableAdapter();
			CrmDataSet.ContactsDataTable contactsTable = contactsAdapter.GetDataByAccountID(account.LocalID);
			Utility.SyncEngine.SyncItems<CrmDataSet.ContactsRow>(contactFolder, contactsTable.Rows, Utility.SyncDirection.ItemToOutlook);
			contactsAdapter.Update(contactsTable);
		}
        
		private void SyncActivities(MSOutlook.MAPIFolder accountFolder, CrmDataSet.AccountsRow account)
		{
			MSOutlook.MAPIFolder activityFolder = Utility.Folder.CreateFolder(
				accountFolder,
				Properties.Resources.ActivitiesFolderName,
				MSOutlook.OlDefaultFolders.olFolderTasks);
			_itemManager.RegisterCustomForm(activityFolder, typeof(ItemForms.ActivityForm));

			CrmDataSetTableAdapters.ActivitiesTableAdapter activitiesAdapter = new CrmDataSetTableAdapters.ActivitiesTableAdapter();
			//CrmDataSet.ActivitiesDataTable activitiesTable = activitiesAdapter.GetDataByAccountID(account.LocalID);
            CrmDataSet.ActivitiesDataTable activitiesTable = new CrmDataSet.ActivitiesDataTable();
            activitiesAdapter.FillByAccountID(activitiesTable, account.LocalID);
			Utility.SyncEngine.SyncItems<CrmDataSet.ActivitiesRow>(activityFolder, activitiesTable.Rows, Utility.SyncDirection.ItemToOutlook);
			activitiesAdapter.Update(activitiesTable);

            MSOutlook.View activityView = activityFolder.Views[Properties.Resources.ActivitiesViewName];
            if (activityView == null)
                activityView = activityFolder.Views.Add(
                    Properties.Resources.ActivitiesViewName,
                    MSOutlook.OlViewType.olTableView,
                    MSOutlook.OlViewSaveOption.olViewSaveOptionThisFolderEveryone);

            activityView.XML = Properties.Resources.ActivityView;
            activityView.Save();
            activityView.Apply();
        }
        #endregion

        #region OnFolderWrite/Delete Event
        void OnAppointmentWrite(object sender, CancelEventArgs e)
        {
            Utility.ItemAdapter item = (Utility.ItemAdapter)sender;
            if (item.Class != MSOutlook.OlObjectClass.olAppointment)
                throw new NotSupportedException("OnAppointmentWrite can only be called with outlook appointment items");

            item.Save();
            PIMDataSetTableAdapters.AppointmentsTableAdapter appointmentsTableAdapter = new PIMDataSetTableAdapters.AppointmentsTableAdapter();
            PIMDataSet.AppointmentsDataTable appointmentsDataTable = appointmentsTableAdapter.GetDataByOutlookID(item.EntryID);

            bool newRow = false;
            //Create New appointment rows
            if (appointmentsDataTable.Rows.Count == 0)
            {
                PIMDataSet.AppointmentsRow appointmentsRow = appointmentsDataTable.NewAppointmentsRow();
                newRow = true;

                appointmentsRow.LocalID = Guid.NewGuid();
                appointmentsRow.OutlookID = item.EntryID;

                //Get the associated account ID via the parent folder's OutlookID
                MSOutlook.MAPIFolder calendarsFolder = (MSOutlook.MAPIFolder)item.Parent;
                MSOutlook.MAPIFolder personalFolder = (MSOutlook.MAPIFolder)calendarsFolder.Parent;
                PIMDataSetTableAdapters.AccountsTableAdapter accountsTableAdapter
                    = new PIMDataSetTableAdapters.AccountsTableAdapter();
                appointmentsRow.AccountID = (Guid)accountsTableAdapter.GetAccountIDByOutlookID(personalFolder.EntryID);

                appointmentsDataTable.BeginLoadData();
                appointmentsDataTable.AddAppointmentsRow(appointmentsRow);
            }

            Utility.SyncEngine.SyncItem<PIMDataSet.AppointmentsRow>(
                    (PIMDataSet.AppointmentsRow)appointmentsDataTable.Rows[0],
                    item,
                    Utility.SyncDirection.OutlookToItem);

            if (newRow)
                appointmentsDataTable.EndLoadData();
           
            appointmentsTableAdapter.Update(appointmentsDataTable);
            
            item.Display();
        }
        void OnAppointmentDelete(object sender, CancelEventArgs e)
        {
            Utility.ItemAdapter item = (Utility.ItemAdapter)sender;
            if (item.Class != MSOutlook.OlObjectClass.olAppointment)
                throw new NotSupportedException("OnAppointmentDelete can only be called with outlook appointment items");

            PIMDataSetTableAdapters.AppointmentsTableAdapter appointmentsTableAdapter = new PIMDataSetTableAdapters.AppointmentsTableAdapter();
            PIMDataSet.AppointmentsDataTable appointmentDataTable = new PIMDataSet.AppointmentsDataTable();

            appointmentsTableAdapter.DeleteAppointment(item.EntryID, Utility.GlobalClass.AccountID);
            item.Delete();

        }
        
        void OnContactWrite(object sender, CancelEventArgs e)
		{
            try
            {
                Utility.ItemAdapter item = (Utility.ItemAdapter)sender;
                if (item.Class != MSOutlook.OlObjectClass.olContact)
                    throw new NotSupportedException("OnContactWrite can only be called with outlook contact items");
                item.Save();  
                PIMDataSetTableAdapters.ContactsTableAdapter contactsTableAdapter = new PIMDataSetTableAdapters.ContactsTableAdapter();
                PIMDataSet.ContactsDataTable contactsDataTable = contactsTableAdapter.GetDataByOutlookID(item.EntryID);
                
                bool newRow = false;
                //Create New contact rows
                if (contactsDataTable.Rows.Count == 0)
                {
                    //create new row
                    PIMDataSet.ContactsRow contactsRow = contactsDataTable.NewContactsRow();
                    newRow = true;

                    contactsRow.LocalID = Guid.NewGuid();
                    contactsRow.OutlookID = item.EntryID; //insert outlookID
      
                    //Get the associated account ID via the parent folder's OutlookID
                    MSOutlook.MAPIFolder contactsFolder = (MSOutlook.MAPIFolder)item.Parent;
                    MSOutlook.MAPIFolder personalFolder = (MSOutlook.MAPIFolder)contactsFolder.Parent;
                    PIMDataSetTableAdapters.AccountsTableAdapter accountsTableAdapter
                        = new PIMDataSetTableAdapters.AccountsTableAdapter();
                    contactsRow.AccountID = (Guid)accountsTableAdapter.GetAccountIDByOutlookID(personalFolder.EntryID);

                    contactsDataTable.BeginLoadData();
                    contactsDataTable.AddContactsRow(contactsRow);
                }

                Utility.SyncEngine.SyncItem<PIMDataSet.ContactsRow>(
                    (PIMDataSet.ContactsRow)contactsDataTable.Rows[0],
                    item,
                    Utility.SyncDirection.OutlookToItem);
                
                if (newRow)
                    contactsDataTable.EndLoadData();
                contactsTableAdapter.Update(contactsDataTable);
                
                //Update IdenID
                string Email = contactsTableAdapter.GetEmail(item.EntryID);
                if (Email != null)
                {
                    PIMDataSetTableAdapters.AccountsTableAdapter accountsTableAdapter
                        = new PIMDataSetTableAdapters.AccountsTableAdapter();
                    //get IdenID from Email
                    if (accountsTableAdapter.GetIdenID(Email) != null)
                        //update IdenID from accountID
                        contactsTableAdapter.UpdateIdenID(accountsTableAdapter.GetIdenID(Email), item.EntryID);
                }
                item.Display();
            }
            catch (Exception)
            {
                e.Cancel = true;
            }
        }

        void OnContactDelete(object sender, CancelEventArgs e)
        {
            Utility.ItemAdapter item = (Utility.ItemAdapter)sender;
            if (item.Class != MSOutlook.OlObjectClass.olContact)
                throw new NotSupportedException("OnContactDelete can only be called with outlook contact items");

            PIMDataSetTableAdapters.ContactsTableAdapter contactsTableAdapter = new PIMDataSetTableAdapters.ContactsTableAdapter();
            PIMDataSet.ContactsDataTable contactsDataTable = new PIMDataSet.ContactsDataTable();
            
            contactsTableAdapter.DeleteContact(item.EntryID, Utility.GlobalClass.AccountID);
            item.Delete();

        }
        #endregion

        

        public static void ConfigureDataDirectory(Type t)
		{
			//Need to set the DataDictionary property of the domain so that we can locate the database file
#if !INSTALL
            //If INSTALL is not set, the DB is in the same directory as the code
			if (AppDomain.CurrentDomain.GetData("DataDirectory") == null)
			{
				string dataDirectory = System.IO.Path.GetDirectoryName(t.Assembly.Location);
				AppDomain.CurrentDomain.SetData("DataDirectory", dataDirectory);
			}
#else
            //If INSTALL is set, the DB is in the 
            //C:\Documents and Settings\<username>\Application Data\Sample.Outlook.CRMIntegration folder
			string dataDirectory = System.IO.Path.Combine(
				Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
				"Sample.Outlook.CRMIntegration");
			AppDomain.CurrentDomain.SetData("DataDirectory", dataDirectory);
#endif
        }

		#region VSTO generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InternalStartup()
		{
			this.Startup += new System.EventHandler(ThisApplication_Startup);
			this.Shutdown += new System.EventHandler(ThisApplication_Shutdown);
		}

		#endregion
	}
}
